/**
 * Notes: 云数据库基础操作
 * Ver : CCMiniCloud Framework 2.0.1 ALL RIGHTS RESERVED BY cclinux0730 (wechat)
 * Date: 2020-09-05 04:00:00 
 */

const cloudBase = require('./cloud_base.js');

// 云数据库实例
let db = null;

/**
 * 获取云数据库实例
 */
function getDatabase() {
	if (db) return db;
	
	db = cloudBase.getDatabase();
	return db;
}

/**
 * 获取云实例
 */
function getCloud() {
	return cloudBase.getCloud();
}

/**
 * 获取集合对象
 * @param {string} collectionName 集合名称
 */
function getCollection(dbName) {
	let cloud = getCloud();
	let db = cloud.database();
	console.log(`[cloud_db.getCollection] 获取集合: ${dbName}`);
	
	let collection = null;
	try {
		collection = db.collection(dbName);
		console.log(`[cloud_db.getCollection] 集合获取成功: ${dbName}`);
	} catch (error) {
		console.error(`[cloud_db.getCollection] 获取集合出错: ${error.message}`);
		throw error;
	}
	
	return collection;
}

/**
 * 获取集合聚合对象
 * @param {string} collectionName 集合名称
 */
function getAggregateCollection(collectionName) {
	const collection = getDatabase().collection(collectionName);
	const aggregate = collection.aggregate();
	return aggregate;
}

/**
 * 获取聚合对象
 */
function getAggregateCommand() {
	return getDatabase().command.aggregate;
}

/**
 * 获取命令对象
 */
function getCommand() {
	return getDatabase().command;
}

/**
 * 获取服务器时间
 */
function getServerDate() {
	return getDatabase().serverDate();
}

module.exports = {
    getCloud,
    getDatabase,
    getCollection,
    getAggregateCommand,
    getCommand,
    getServerDate,
    getAggregateCollection
}; 